import os
import time
import shutil
from datetime import datetime
import schedule

LOG_FILE = "pyBackuper.log"
TARGET = "E:\\Game\\Steamcmd\\steamapps\\common\\PalServer\\Pal\\Saved"
TARGET_TYPE = "directory" 
TIMER = "04:00:00" 
TIMER_MODE = "datetime"


def backup_operator() -> None:
    if TARGET_TYPE == "directory":
        # Edit new backup file|folder name here ↓
        new_target = TARGET + "-" + datetime.now().strftime("%y%m%d_%H%M%S")
        shutil.copytree(TARGET, new_target)
        mylog("[INFO] Finished backing up directory " + TARGET + " to " + new_target)
    elif TARGET_TYPE == "file":
        path = os.path.dirname(TARGET)
        # parent = os.path.basename(target)
        file_name, file_ext = os.path.splitext(TARGET)
        # Edit new backup file|folder name here ↓
        new_filename = (
            file_name + "-" + datetime.now().strftime("%y%m%d_%H%M%S") + file_ext
        )
        new_target = os.path.join(path, new_filename)
        shutil.copy(TARGET, new_target)
        mylog("[INFO] Finished backing up file " + TARGET + " to " + new_target)
    else:
        mylog("[ERROR] invalid path: not a file or directory")
        exit(-1)
 

def mylog(s: str = ""):
    s = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]" + s
    print(s)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(s + "\n")
        f.close()


if __name__ == "__main__":
    os.system("title pyBackuper")
    
    schedule.run_pending()
    if TIMER_MODE == "minute":
        schedule.every(TIMER).minutes.do(backup_operator)
        mylog(
            f"[Init] Program will backup ({TARGET_TYPE}){TARGET} every {TIMER} minutes"
        )
    elif TIMER_MODE == "datetime":
        schedule.every().day.at(TIMER).do(backup_operator)
        mylog(
            f"[Init] Program will backup ({TARGET_TYPE}){TARGET} at {TIMER} everyday"
        )
    else:
        mylog("[ERROR] Invalid timer mode")
        exit(-1)
    while True:
        schedule.run_pending()
        time.sleep(1)
